//
//  IGMultipleDrawingsBuyVC.m
//  jingdongfang
//
//  Created by boectoswteam on 2018/5/7.
//  Copyright © 2018年 BOE-SBG-CTO. All rights reserved.
//
//多图打包购买

typedef NS_ENUM(NSUInteger,IGPAYTYPE) {
    ALIPAY,
    WECHATPAY
};

#import "IGMultipleDrawingsBuyVC.h"
#import "IGUnPaidDrawingCell.h"
#import "IGPayTypeCell.h"
#import "WeiXinPayManager.h"
#import "AliPayManager.h"
#import "IGMultipleBuyApi.h"//订单生成API
#import "IGPaymentApi.h"    //付款API
#import "BuySuccViewController.h"
#import "OrderXQViewController.h"
#import "IGPaymentResultQueryApi.h" //支付结果API

@interface IGMultipleDrawingsBuyVC ()<UITableViewDelegate,UITableViewDataSource>
{
    NSArray *payTypeArray;
}
@property (nonatomic, strong) UITableView *drawingTableView;
@property (nonatomic, assign) NSInteger selectPayType;
@property (nonatomic, strong) UIButton *buyBtn;
@property (nonatomic, strong) IGMultipleBuyApi *buyApi;
@property (nonatomic, strong) IGPaymentApi *payApi;
@property (nonatomic, copy) NSString *totalMoney;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, copy) NSString *newOrderId;
@end

@implementation IGMultipleDrawingsBuyVC

#pragma mark - lifeCycle
- (void)viewDidLoad {
    [super viewDidLoad];
//    self.title = @"限量收藏";
    self.title = NSLocalizedString(@"Limited Collect", nil);
    _selectPayType = ALIPAY;
    payTypeArray = @[@{@"payIcon":@"alipay",@"payName":NSLocalizedString(@"Alipay",nil)},@{@"payIcon":@"wechatpay",@"payName":NSLocalizedString(@"WeChat",nil)}];
    [self initDrawingTableView];
    [self.drawingTableView registerNib:[UINib nibWithNibName:@"IGUnPaidDrawingCell" bundle:nil] forCellReuseIdentifier:@"IGUnPaidDrawingCell"];
    [self.drawingTableView registerNib:[UINib nibWithNibName:@"IGPayTypeCell" bundle:nil] forCellReuseIdentifier:@"IGPayTypeCell"];
    [self.view addSubview:self.buyBtn];
    
    [self loadunPaidPaintingList];
    //注册监听-支付宝
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(dealAlipayResult:) name:@"alipayResult" object:nil];
    //注册监听-微信
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(dealWXpayResult:) name:@"WXpayresult" object:nil];
}

-(void)loadunPaidPaintingList{
    self.buyApi = [[IGMultipleBuyApi alloc]init];
    self.buyApi.type = self.type;
    self.buyApi.thingId = self.thingId;
    
    __weak typeof(self) weakSelf = self;
    [self.buyApi startWithDecodeClass:[IGMultipleBuyResponse class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (error) {
            [self presentMessageTips:error.localizedDescription];
            return ;
        }
        if (responseObject) {
            IGMultipleBuyResponse *response = responseObject;
            IGMultipleBuyModel *model = response.data;
            weakSelf.totalMoney = model.priceActual;
            weakSelf.dataArray = [NSMutableArray arrayWithArray:model.productList];
            [weakSelf.drawingTableView reloadData];
        }
    }];
}

-(void)initDrawingTableView{
    _drawingTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, KSCREENHEIGHT -44) style:UITableViewStyleGrouped];
    _drawingTableView.delegate = self;
    _drawingTableView.dataSource = self;
    _drawingTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    [self.view addSubview:_drawingTableView];
}

#pragma mark - UITableViewDelegate && UITableViewDateSource

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    switch (section) {
        case 0:
        {
            UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, 35)];
            UILabel *titleL = [[UILabel alloc]initWithFrame:CGRectMake(0, 5, KSCREENWIDTH, 30)];
            titleL.backgroundColor = [UIColor whiteColor];
            titleL.font = [UIFont font18];
            titleL.text = @"以下作品未收藏";
            titleL.textAlignment = NSTextAlignmentCenter;
            [view addSubview:titleL];
            return view;
        }
            break;
        case 2:
        {
            UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, 35)];
            UILabel *titleL1 = [[UILabel alloc]initWithFrame:CGRectMake(0, 5 , KSCREENWIDTH, 30)];
            titleL1.backgroundColor = [UIColor whiteColor];
            [view addSubview:titleL1];
            UILabel *titleL2 = [[UILabel alloc]initWithFrame:CGRectMake(15, 2 , KSCREENWIDTH, 30)];
            titleL2.font = [UIFont font18];
            titleL2.text = @"选择支付方式";
            titleL2.textAlignment = NSTextAlignmentLeft;
            [titleL1 addSubview:titleL2];
            return view;
        }
            break;
    }
    return nil;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    switch (indexPath.section) {
        case 0:
        {
            IGUnPaidDrawingCell *unPaidcell = [tableView dequeueReusableCellWithIdentifier:@"IGUnPaidDrawingCell"];
            unPaidcell.selectionStyle = UITableViewCellSelectionStyleNone;
            unPaidcell.model = self.dataArray[indexPath.row];
//            unPaidcell.drawingName.text = @"我喜欢的作品";
//            unPaidcell.drawingAuthor.text = @"高尔基";
//            unPaidcell.drawingPrice.text = @"￥123";
            return unPaidcell;
        }
            break;
        case 1:
        {
            UITableViewCell *totalCell = [tableView dequeueReusableCellWithIdentifier:@"totalCell"];
            totalCell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"totalCell"];
            totalCell.selectionStyle = UITableViewCellSelectionStyleNone;
            UILabel *totalLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, KSCREENWIDTH - 15, 44)];
            totalLabel.textAlignment = NSTextAlignmentRight;
            NSMutableAttributedString *totalMoney = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@ %@",NSLocalizedString(@"合计:", nil),self.totalMoney]];
            [totalMoney addAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont boldSystemFontOfSize:16],NSFontAttributeName,RGB(74, 169, 227),NSForegroundColorAttributeName, nil] range:NSMakeRange(NSLocalizedString(@"合计:", nil).length+1, self.totalMoney.length)];
            totalLabel.attributedText = totalMoney;
            [totalCell addSubview:totalLabel];
            return totalCell;
        }
            break;
        case 2:
        {
            IGPayTypeCell *payTypeCell = [tableView dequeueReusableCellWithIdentifier:@"IGPayTypeCell"];
            payTypeCell.dataDic = payTypeArray[indexPath.row];
            if (_selectPayType == indexPath.row + 1) {
                payTypeCell.isSelectedIcon.image = [UIImage imageNamed:@"pushiGallery_Selected"];
            } else {
                payTypeCell.isSelectedIcon.image = [UIImage imageNamed:@"pushiGallery_Normal"];
            }
            return payTypeCell;
        }
            break;
    }
    return nil;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    switch (section) {
        case 0:
            return self.dataArray.count?self.dataArray.count:0;
            break;
        case 1:
            return 1;
            break;
        case 2:
            return 2;
            break;
    }
    return 0;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    switch (indexPath.section) {
        case 0:
            return 64;
            break;
        case 1:
            return 44;
            break;
        case 2:
            return 44;
            break;
    }
    return 0;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0 || section == 2) {
        return 35;
    }
    return 0.1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    if (indexPath.section == 2) {
        _selectPayType = indexPath.row+1;
        [tableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationNone];
    }
}

#pragma mark - 支付宝支付状态回调
-(void)dealAlipayResult:(NSNotification*)notification{
    NSString*result=notification.object;
    if([result isEqualToString:@"9000"]){
        //在这里写支付成功之后的回调操作
        //        NSLog(@"支付宝支付成功");
        IGPaymentResultQueryApi *api = [IGPaymentResultQueryApi new];
        api.orderId = self.newOrderId;
        api.payPlatCode = @"alipay";
        [api startWithDecodeClass:[IGPaymentResultQueryResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
            
        }];
        @KWeakObj(self)
        BuySuccViewController *vc = [[BuySuccViewController alloc] initWithNibName:@"BuySuccViewController" bundle:nil];
        @KWeakObj(vc)
        vc.orderId = self.newOrderId;
        vc.backBtnClick = ^{
            [selfWeak.navigationController popViewControllerAnimated:YES];
        };
        vc.orderBtnClick = ^{
            [vcWeak back];
            OrderXQViewController *vc1 = [[OrderXQViewController alloc] init];
            vc1.oid = self.newOrderId;
            vc1.isMyBuy = YES;
            [UIViewController ig_pushViewController:vc1 animated:YES];
        };
        [selfWeak presentViewController:vc animated:YES completion:nil];
    }
    else
    {
        //在这里写支付失败之后的回调操作
        //DeLog(@"支付宝支付失败");
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark - 微信支付状态的回调

-(void)dealWXpayResult:(NSNotification*)notification{
    NSString*result=notification.object;
    if([result isEqualToString:@"1"])
    {
        //在这里写支付成功之后的回调操作
        //        NSLog(@"微信支付成功");
        IGPaymentResultQueryApi *api = [IGPaymentResultQueryApi new];
        api.orderId = self.newOrderId;
        api.payPlatCode = @"wxpay";
        [api startWithDecodeClass:[IGPaymentResultQueryResp class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
            if (responseObject)
            {
            }
        }];
        @KWeakObj(self)
        BuySuccViewController *vc = [[BuySuccViewController alloc] initWithNibName:@"BuySuccViewController" bundle:nil];
        @KWeakObj(vc)
        vc.orderId = self.newOrderId;
        vc.backBtnClick = ^{
            [selfWeak.navigationController popViewControllerAnimated:YES];
        };
        vc.orderBtnClick = ^{
            [vcWeak back];
            OrderXQViewController *vc1 = [[OrderXQViewController alloc] init];
            vc1.oid = self.newOrderId;
            vc1.isMyBuy = YES;
            [UIViewController ig_pushViewController:vc1 animated:YES];
        };
        [selfWeak presentViewController:vc animated:YES completion:nil];
    }else{
        //在这里写支付失败之后的回调操作
        // DeLog(@"微信支付失败");
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark - private event

-(void)payMoney{
    
    self.payApi = [[IGPaymentApi alloc]init];
    self.payApi.price = self.totalMoney;
    self.payApi.payPlatCode = (self.selectPayType==ALIPAY)?@"alipay":@"wxpay";
    self.payApi.ifUseArtPoint = @"0";
    self.payApi.clientIp = @"iOS";
    self.payApi.pIds = self.thingId;
    
    __weak typeof(self) weakSelf = self;
    [self.payApi startWithDecodeClass:[IGPaymentResponse class] CompletionBlockWithSuccess:^(id responseObject, NSError *error) {
        if (responseObject) {
            IGPaymentResponse *response = responseObject;
            IGPaymentModel *model = response.data;
            self.newOrderId = model.orderId;
            if ([model.method isEqualToString:@"paySuccess"]) {
                //跳转支付成功页面
                BuySuccViewController *vc = [[BuySuccViewController alloc] initWithNibName:@"BuySuccViewController" bundle:nil];
                @KWeakObj(vc)
                vc.orderId = model.orderId;
                vc.backBtnClick = ^{
//                    [UIViewController ig_popViewController:[XiangQingViewController class]];
                };
                vc.orderBtnClick = ^{
                    [vcWeak back];
                    OrderXQViewController *vc1 = [[OrderXQViewController alloc] init];
                    vc1.oid = model.orderId;
                    vc1.isMyBuy = YES;
                    [UIViewController ig_pushViewController:vc1 animated:YES];
                };
                [weakSelf presentViewController:vc animated:YES completion:nil];
                
            } else if ([model.method isEqualToString:@"toCashier"]){
                //跳转收银台
                if (_selectPayType == ALIPAY)
                {
                    [[AliPayManager sharedAliPayManager] payWithDic:model.ResBean];
                    return;
                }
                else if (_selectPayType == WECHATPAY)
                {
                    NSDictionary *dic = model.ResBean[@"data"];
                    if (dic)
                    {
                        WXProduct * wx  = [WXProduct new];
                        wx.package = dic[@"package"];
                        wx.noncestr = dic[@"noncestr"];
                        wx.appid = dic[@"appid"];
                        wx.partnerid = dic[@"partnerid"];
                        wx.prepayid = dic[@"prepayid"];
                        wx.timestamp = [dic[@"timestamp"] longLongValue];
                        wx.sign = dic[@"sign"];
                        [[WeiXinPayManager sharedManager]weiXinPay:wx];
                        return;
                    }
                }
                
            }
        }

    }];
    
}

#pragma mark - set

-(UIButton *)buyBtn{
    if (!_buyBtn) {
        _buyBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _buyBtn.frame = CGRectMake(0, KSCREENHEIGHT - 44, KSCREENWIDTH, 44);
        _buyBtn.backgroundColor = RGB(69, 174, 227);
        [_buyBtn setTitle:NSLocalizedString(@"Go to the payment", nil) forState:UIControlStateNormal];
        [_buyBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_buyBtn addTarget:self action:@selector(payMoney) forControlEvents:UIControlEventTouchUpInside];
    }
    return _buyBtn;
}

-(NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

-(NSString *)totalMoney{
    if (!_totalMoney) {
        _totalMoney = [[NSString alloc]init];
    }
    return _totalMoney;
}

-(NSString *)newOrderId{
    if (!_newOrderId) {
        _newOrderId = [[NSString alloc]init];
    }
    return _newOrderId;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
